/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author DIVID
 */
public class TCPEchoServer {

    public final static int defaultPort = 2014;

    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(defaultPort);
            System.out.println("Server dang hoat dong tai cong: " + defaultPort);
            while (true) {
                try {
                    Process p = new Process(ss.accept());
                    p.start();
                } catch (IOException ex) {
                    Logger.getLogger(TCPEchoServer.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(TCPEchoServer.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

class Process extends Thread {

    Socket s;

    public Process() {
    }

    public Process(Socket s) {
        this.s = s;
    }

    @Override
    public synchronized void start() {
        try {
            OutputStream os = s.getOutputStream();
            InputStream is = s.getInputStream();
            int ch = 0;
            while (true) {
                ch = is.read();
                System.out.println(ch);
                if (ch == -1) {
                    break;
                }
                os.write(ch);
            }
            s.close();
        } catch (IOException e) {
            System.out.println("ERROR: " + e);
        }
    }

}
